package top.zhdev.community.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.zhdev.community.entity.*;
import top.zhdev.community.event.EventProducer;
import top.zhdev.community.service.CommentService;
import top.zhdev.community.service.DiscussPostService;
import top.zhdev.community.service.LikeService;
import top.zhdev.community.service.UserService;
import top.zhdev.community.utils.CommunityConstant;
import top.zhdev.community.utils.CommunityUtil;
import top.zhdev.community.utils.HostHolder;
import top.zhdev.community.utils.RedisKeyUtil;

import javax.annotation.Resource;
import java.util.*;

/**
 * 帖子处理
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostController.class);

    private DiscussPostService discussPostService;
    private UserService userService;
    private LikeService likeService;
    private HostHolder hostHolder;
    private CommentService commentService;
    private EventProducer eventProducer;

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    public void setDiscussPostService(DiscussPostService discussPostService){
        this.discussPostService = discussPostService;
    }

    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    @Autowired
    public void setLikeService(LikeService likeService){
        this.likeService = likeService;
    }

    @Autowired
    public void setHostHolder(HostHolder hostHolder){
        this.hostHolder = hostHolder;
    }

    @Autowired
    public void setCommentService(CommentService commentService){
        this.commentService = commentService;
    }

    @Autowired
    public void setEventProducer(EventProducer eventProducer) {
        this.eventProducer = eventProducer;
    }

    @GetMapping("/detail/{discussPostId}")
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page page){
        // 帖子
        DiscussPost post = discussPostService.getDiscussPostById(discussPostId);
        model.addAttribute("post",post);

        // 作者
        User user = userService.getUserById(post.getUserId());
        model.addAttribute("user",user);

        // 点赞数量
        long likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_POST,discussPostId);
        model.addAttribute("likeCount",likeCount);

        // 点赞状态
        int likeStatus = hostHolder.getUser() == null ? 0 :
                likeService.getEntityLikeStatus(ENTITY_TYPE_POST,discussPostId,hostHolder.getUser().getId());

        model.addAttribute("likeStatus",likeStatus);

        // 评论分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setRows(post.getCommentCount());

        // 评论：给帖子的评论
        // 回复：给评论的评论
        // 评论列表
        List<Comment> commentList = commentService.getCommentsByEntity(ENTITY_TYPE_POST,post.getId(),
                page.getOffset(),page.getLimit());
        // 评论VO列表
        List<Map<String,Object>> commentVoList = new ArrayList<>();
        if(commentVoList != null){
            for (Comment comment : commentList){
                // 评论VO
                Map<String,Object> commentVo = new HashMap<>();
                // 评论
                commentVo.put("comment",comment);
                // 作者
                commentVo.put("user",userService.getUserById(comment.getUserId()));
                // 评论点赞数量
                likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_COMMENT,comment.getId());
                commentVo.put("likeCount",likeCount);
                // 点赞状态，需要判断当前用户是否登录，没有登录无法点赞
                likeStatus = hostHolder.getUser() == null ? 0 :
                        likeService.getEntityLikeStatus(ENTITY_TYPE_COMMENT,comment.getId(),hostHolder.getUser().getId());
                logger.info("DiscussPostController的点赞状态{}",likeStatus);
                commentVo.put("likeStatus",likeStatus);
                // 回复列表
                List<Comment> replyList = commentService.getCommentsByEntity(
                        ENTITY_TYPE_COMMENT,comment.getId(),0,Integer.MAX_VALUE
                );
                // 回复列表VO
                List<Map<String,Object>> replyVoList = new ArrayList<>();
                if(replyList != null){
                    for(Comment reply : replyList){
                        Map<String,Object> replyVo = new HashMap<>();
                        // 回复
                        replyVo.put("reply",reply);
                        // 作者
                        replyVo.put("user",userService.getUserById(reply.getUserId()));
                        // 回复目标
                        User target = reply.getTargetId() == 0 ? null : userService.getUserById(reply.getTargetId());
                        replyVo.put("target",target);
                        // 点赞数量
                        likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_COMMENT,reply.getId());
                        replyVo.put("likeCount",likeCount);
                        // 点赞状态，需要判断当前用户是否登录，没有登录无法点赞（获取当前用户的的登录状态，用于接下来的操作）
                        likeStatus = hostHolder.getUser() == null ? 0 : likeService.getEntityLikeStatus(
                                ENTITY_TYPE_COMMENT,reply.getId(),hostHolder.getUser().getId()
                        );
                        replyVo.put("likeStatus",likeStatus);

                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys",replyVoList);
                // 回复数量
                int repltCount = commentService.getCommentCount(ENTITY_TYPE_COMMENT,comment.getId());
                commentVo.put("replyCount",repltCount);
                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments",commentVoList);
        return "site/discuss-detail";
    }

    @PostMapping ("/add")
    @ResponseBody
    public String addDiscussPost(String title,String content){
        User user = hostHolder.getUser();
        if(user == null){
            return CommunityUtil.getJSONString(403,"你还没有登录哦！");
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setType(user.getType());
        post.setStatus(0);
        post.setTitle(title);
        post.setContent(content);
        post.setCommentCount(0);
        post.setCreateTime(new Date());
        discussPostService.addDiscussPost(post);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(post.getId());
        // 调用 kafka
        eventProducer.sendEvent(event);
        // 计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey,post.getId());

        // 报错的情况，将来同一处理
        return CommunityUtil.getJSONString(0,"发布成功");

    }

    /**
     * 删除帖子，实际上知只是做了一个删除标记
     * @param discussPostId
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public String setDelete(int discussPostId){
        // 删除，更新帖子状态
        discussPostService.setPostStatus(discussPostId,2);
        // 修改在elasticSearch服务器中的状态
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPostId);
        eventProducer.sendEvent(event);
        return CommunityUtil.getJSONString(0);

    }

    /**
     * 帖子加精（更改状态）
     * @param discussPostId
     * @return
     */
    @PostMapping("/wonderful")
    @ResponseBody
    public String setWonderful(int discussPostId){
        discussPostService.setPostStatus(discussPostId,1);
        // 修改ElasticSearch中帖子的状态
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityType(discussPostId);
        eventProducer.sendEvent(event);
        // 计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey,discussPostId);
        return CommunityUtil.getJSONString(0);
    }

    /**
     * 置顶帖子（更改帖子状态）
     * @param discussPostId
     * @return
     */
    @PostMapping("/top")
    @ResponseBody
    public String setTop(int discussPostId){
        discussPostService.setPostType(discussPostId,1);
        // 修改在elasticsearch服务器中的状态
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPostId);
        eventProducer.sendEvent(event);
        return CommunityUtil.getJSONString(0);
    }
}
